package com.iteima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.iteima.reggie.common.BaseContext;
import com.iteima.reggie.common.R;
import com.iteima.reggie.entity.Dish;
import com.iteima.reggie.entity.ShoppingCart;
import com.iteima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加菜品/套餐到购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<String> add(@RequestBody ShoppingCart shoppingCart){

        log.info(shoppingCart.toString());
        Long userID = BaseContext.getCurrentId();
        shoppingCart.setUserId(userID);
        shoppingCart.setCreateTime(LocalDateTime.now());
        shoppingCart.setNumber(1);
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userID);
        //判断购物车中是否含有该菜品/套餐
        //从购物车中查找该用户下的所有菜品/套餐
        if (shoppingCart.getDishId() != null){
            //传过来的是菜品
            queryWrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());

        }else if(shoppingCart.getSetmealId() != null){
            //传过来的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        //判断该用户下的所有菜品/套餐 是否与传过来的口味以及菜品id一致
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);

        String dishOrSetmealName = shoppingCart.getName();

        String dishFlavor = shoppingCart.getDishFlavor();

        for (ShoppingCart dish : shoppingCartList) {
            if (dish.getName().equals(dishOrSetmealName) && dish.getDishFlavor().equals(dishFlavor) ){
                //口味 菜品都一致         //如果一致就+1
                dish.setNumber(dish.getNumber() + 1);
                shoppingCartService.updateById(dish);
                return R.success("添加成功!");
            }
        }

        //否则新增
        shoppingCartService.save(shoppingCart);

        return R.success("添加成功！");
    }

    /**
     * 列出购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        Long userId = BaseContext.getCurrentId();
        log.info("userId:={}",userId);
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

        return R.success(list);

    }

    @PostMapping("/sub")
    public R<String> sub(@RequestParam String dishId){
        log.info("dishID={}",dishId);
        return null;

    }
}
